package leetcode.D500.T406;

import java.util.Arrays;

class Solution {
    public int[][] reconstructQueue(int[][] people) {
        Arrays.sort(people, (a, b) -> {
            if (a[0] != b[0])
                return b[0] - a[0];
            return a[1] - b[1];
        });
        for (int i=0; i<people.length; ++i) {
            if (people[i][1] < i) {
                int j = i, temp0 = people[i][0], temp1 = people[i][1];
                while (true) {
                    if (j == 0 || temp1 == j)
                        break;
                    people[j][0] = people[j - 1][0];
                    people[j][1] = people[j - 1][1];
                    j--;
                }
                people[j][0] = temp0;
                people[j][1] = temp1;
            }
        }
        return people;
    }
}